package com.zh.zcy.controller;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.zh.zcy.config.Message;
import com.zh.zcy.dto.*;
import com.zh.zcy.entity.Product;
import com.zh.zcy.entity.User;
import com.zh.zcy.entity.ZcySyncOperation;
import com.zh.zcy.redis.RedisUtil;
import com.zh.zcy.service.FrontJsonService;
import com.zh.zcy.service.ThreadService;
import com.zh.zcy.service.UserService;
import com.zh.zcy.untils.SendUrlUtil;
import com.zh.zcy.untils.UserContextUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.UUID;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 接口转发 前端控制器
 * </p>
 *
 * @author zxl
 * @since 2023-02-15
 */
@RestController
@RequestMapping("zcy/wxRecord")
public class FrontJsonController {

    @Autowired
    private FrontJsonService frontJsonService;

    @Autowired
    private UserService userService;

    /**
     * 同步咨询操作
     * @param dto
     */
    @GetMapping("/syncConsultant")
    public String syncConsultant(SyncConsultDto dto){
//        String url = "http://139.129.243.129:18901/mpProjectDeclare/api/track/consultant";
        String url = "https://mp.zicaicloud.com/mpProjectDeclare/api/track/consultant";
        System.out.println(JSONUtil.toJsonStr(dto));
        JSONObject jsonObject = SendUrlUtil.sendPost(url, JSONUtil.parse(dto).toString(),dto.getOpenId());
        ZcySyncOperation save = new ZcySyncOperation();
        save.setBaseId(UUID.randomUUID().toString().replaceAll                                                                                                         ("-",""));
        save.setType("1");
        save.setParam(JSONUtil.toJsonStr(dto));
        save.setResult(JSONUtil.toJsonStr(jsonObject));
        save.setBaseCreateTime(new Date());
        frontJsonService.save(save);
        return jsonObject.toString();
    }

    /**
     * 同步收藏操作
     * @param dto
     */
    @GetMapping("/syncFavorite")
    public String syncFavorite(SyncFavoriteDto dto){
//        String url = "http://139.129.243.129:18901/mpProjectDeclare/api/track/favorite";
        String url = "https://mp.zicaicloud.com/mpProjectDeclare/api/track/favorite";

        JSONObject jsonObject = SendUrlUtil.sendPost(url, JSONUtil.parse(dto).toString(),dto.getOpenId());
        ZcySyncOperation save = new ZcySyncOperation();
        save.setBaseId(UUID.randomUUID().toString().replaceAll("-",""));
        save.setType("2");
        save.setParam(JSONUtil.toJsonStr(dto));
        save.setResult(JSONUtil.toJsonStr(jsonObject));
        save.setBaseCreateTime(new Date());
        frontJsonService.save(save);
        return jsonObject.toString();
    }

    /**
     * 同步政策匹配
     * @param dto
     */
    @GetMapping("/syncPolicyMatch")
    public String syncPolicyMatch(SyncPolicyMatchDto dto){
//        String url = "http://139.129.243.129:18901/mpProjectDeclare/api/track/policyMatch";
        String url = "https://mp.zicaicloud.com/mpProjectDeclare/api/track/policyMatch";

        JSONObject jsonObject = SendUrlUtil.sendPost(url, JSONUtil.parse(dto).toString(),dto.getOpenId());
        ZcySyncOperation save = new ZcySyncOperation();
        save.setBaseId(UUID.randomUUID().toString().replaceAll("-",""));
        save.setType("3");
        save.setParam(JSONUtil.toJsonStr(dto));
        save.setResult(JSONUtil.toJsonStr(jsonObject));
        save.setBaseCreateTime(new Date());
        frontJsonService.save(save);
        return jsonObject.toString();
    }

    /**
     * 同步浏览操作
     * @param dto
     */
    @GetMapping("/syncView")
    public String syncView(SyncViewDto dto){
//        String url = "http://139.129.243.129:18901/mpProjectDeclare/api/track/view";
        String url = "https://mp.zicaicloud.com/mpProjectDeclare/api/track/view";

        JSONObject jsonObject = SendUrlUtil.sendPost(url, JSONUtil.parse(dto).toString(),dto.getOpenId());
        ZcySyncOperation save = new ZcySyncOperation();
        save.setBaseId(UUID.randomUUID().toString().replaceAll("-",""));
        save.setType("4");
        save.setParam(JSONUtil.toJsonStr(dto));
        save.setResult(JSONUtil.toJsonStr(jsonObject));
        save.setBaseCreateTime(new Date());
        frontJsonService.save(save);
        return jsonObject.toString();
    }

    @Autowired
    private ThreadService threadService;
    @GetMapping("/threadTest/{id}")
    public Message threadTest(@PathVariable String id){
        // sendTask1和sendTask2方法会异步执行
        threadService.sendTask1();
        threadService.sendTask2();
        // sendTask3是新的线程配置
        threadService.sendTask3();
        return Message.success(id);
    }

    @GetMapping("/threadTest2/{name}")
    public String CompletableFuture(@PathVariable String name){
        // 自定义线程池
        ThreadPoolExecutor executor = new ThreadPoolExecutor(5,
                10,
                15,
                TimeUnit.SECONDS,
                new ArrayBlockingQueue<>(5),
                new ThreadPoolExecutor.CallerRunsPolicy());
        // 异步执行1-使用自定义线程池
        CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
            // 执行逻辑
            try {
                Thread.sleep(5000);
                System.out.println("1睡醒了。。。");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        },executor);
        // 异步执行2-使用默认线程池
        CompletableFuture<Void> future2 = CompletableFuture.runAsync(() -> {
            // 执行逻辑
            try {
                Thread.sleep(10000);
                System.out.println("2睡醒了。。。");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        return name;
    }

    @GetMapping("/setKey/{name}")
    public String setKey(@PathVariable String name){
        RedisUtil.set("name",name);
        RedisUtil.setIfAbsent("king","zxl");
        return name;
    }
    @GetMapping("/getKey/{name}")
    public String getKey(@PathVariable String name){
        String s = RedisUtil.get("name").toString();
        return s;
    }

    /**
     * 对控制器 RequestMapping方法统一处理
     * @param dto
     * @return
     */
    @RequestMapping(value = "/requestDeal",method = RequestMethod.POST,consumes = MediaType.APPLICATION_JSON_VALUE)
    public String requestDeal(@RequestBody SyncViewDto dto){
        return "success";
    }

    /**
     * 分布式锁测试
     * @param dto
     * @return
     */
    @RequestMapping(value = "/buy",method = RequestMethod.POST,consumes = MediaType.APPLICATION_JSON_VALUE)
    public String getName(@RequestBody BuyDto dto){
        Product product = frontJsonService.selectById(dto);
        return product.toString();
    }

    /**
     * 测试springboot最大能同时处理多少请求
     * @return
     */
    @GetMapping("/testMaxRequest")
    public String testMaxRequest() throws InterruptedException {
        Thread.sleep(2000);
        return "success";
    }

    @RequestMapping(value = "/testThreadLocal",method = RequestMethod.POST,consumes = MediaType.APPLICATION_JSON_VALUE)
    public String testThreadLocal(@RequestBody UserDto dto) throws InterruptedException {
        User user = new User(dto.getId(),dto.getName(),dto.getAge());
        UserContextUtil.setUser(user);
        //测试从上下文中获取
        User u = userService.testGetUserByContext();
        return u.toString();
    }

}



